using System;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using TEngine;
using UnityEngine;

namespace GameLogic
{
    public static class SettingsExtensions
    {
        private static GameConfig _gameConfig;
        private static Task<GameConfig> _loadingTask;
        private static readonly object _lock = new object();

        public static async UniTask<GameConfig> GetGameConfig(this Settings settings)
        {
            // 如果已经加载完成，直接返回
            if (_gameConfig != null)
            {
                return _gameConfig;
            }

            // 检查是否正在加载
            if (_loadingTask != null)
            {
                return await _loadingTask;
            }

            lock (_lock)
            {
                // 再次检查，防止竞态条件
                if (_loadingTask == null)
                {
                    _loadingTask = LoadGameConfigAsync();
                }
            }

            return await _loadingTask;
        }

        private static async Task<GameConfig> LoadGameConfigAsync()
        {
            try
            {
                var resourceModule = ModuleSystem.GetModule<IResourceModule>();
                _gameConfig = await resourceModule.LoadAssetAsync<GameConfig>("GameConfig");

                if (_gameConfig == null)
                {
                    Log.Error("GameConfig not found, creating default config");
                    // 创建默认配置作为回退
                    var defaultConfig = ScriptableObject.CreateInstance<GameConfig>();
                    return defaultConfig;
                }

                return _gameConfig;
            }
            catch (Exception ex)
            {
                Log.Error("Failed to load GameConfig: {0}.", ex.Message);

                // 创建默认配置作为回退
                var defaultConfig = ScriptableObject.CreateInstance<GameConfig>();
                return defaultConfig;
            }
        }
    }
}